package org.aplombh.java.interview.newcoder;

import java.util.Stack;

public class NC52_有效括号序列 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param s string字符串
     * @return bool布尔型
     */
    public boolean isValid(String s) {
        char[] chars = {' ', '(', ')', '{', '}', '[', ']'};
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            for (int j = 1; j <= 3; j++) {
                if (s.charAt(i) == chars[2 * j - 1]) {
                    stack.push(s.charAt(i));
                    break;
                }
                if (s.charAt(i) == chars[2 * j]) {
                    if (stack.empty())
                        return false;
                    char pop = stack.pop();

                    if (pop != chars[2 * j - 1])
                        return false;
                    break;
                }
            }
        }
        return stack.empty();
    }
}